home *** CD-ROM | disk | FTP | other *** search
/ Cream of the Crop 1 / Cream of the Crop 1.iso / PROGRAM / DJLSR106.ARJ / STRTOD.C < prev    next >
C/C++ Source or Header  |  1992-03-02  |  2KB  |  104 lines

  1. /*
  2. ** Copyright (C) 1991 DJ Delorie, 24 Kirsten Ave, Rochester NH 03867-2954
  3. **
  4. ** This file is distributed under the terms listed in the document
  5. ** "copying.dj", available from DJ Delorie at the address above.
  6. ** A copy of "copying.dj" should accompany this file; if not, a copy
  7. ** should be available from where this file was obtained.  This file
  8. ** may not be distributed without a verbatim copy of "copying.dj".
  9. **
  10. ** This file is distributed WITHOUT ANY WARRANTY; without even the implied
  11. ** warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  12. */
  13.  
  14. #include <math.h>
  15. #include <stdlib.h>
  16.  
  17. double strtod(const char *s, char **sret)
  18. {
  19.   double r;    /* result */
  20.   int e;    /* exponent */
  21.   double d;    /* scale */
  22.   int sign;    /* +- 1.0 */
  23.   int esign;
  24.   int i;
  25.   int flags=0;
  26.  
  27.   r = 0.0;
  28.   sign = 1.0;
  29.   e = 0;
  30.   esign = 1;
  31.  
  32.   while ((*s == ' ') || (*s == '\t'))
  33.     s++;
  34.  
  35.   if (*s == '+')
  36.     s++;
  37.   else if (*s == '-')
  38.   {
  39.     sign = -1;
  40.     s++;
  41.   }
  42.  
  43.   while ((*s >= '0') && (*s <= '9'))
  44.   {
  45.     flags |= 1;
  46.     r *= 10.0;
  47.     r += *s - '0';
  48.     s++;
  49.   }
  50.  
  51.   if (*s == '.')
  52.   {
  53.     d = 0.1;
  54.     s++;
  55.     while ((*s >= '0') && (*s <= '9'))
  56.     {
  57.       flags |= 2;
  58.       r += d * (*s - '0');
  59.       s++;
  60.       d /= 10.0;
  61.     }
  62.   }
  63.  
  64.   if (flags == 0)
  65.   {
  66.     if (sret) *sret = s;
  67.     return 0;
  68.   }
  69.  
  70.   if ((*s == 'e') || (*s == 'E'))
  71.   {
  72.     s++;
  73.     if (*s == '+')
  74.       s++;
  75.     else if (*s == '-')
  76.     {
  77.       *s++;
  78.       esign = -1;
  79.     }
  80.     if ((*s < '0') || (*s > '9'))
  81.     {
  82.       if (sret) *sret = s;
  83.       return r;
  84.     }
  85.  
  86.     while ((*s >= '0') && (*s <= '9'))
  87.     {
  88.       e *= 10.0;
  89.       e += *s - '0';
  90.       s++;
  91.     }
  92.   }
  93.  
  94.   if (esign < 0)
  95.     for (i = 1; i <= e; i++)
  96.       r /= 10.0;
  97.   else
  98.     for (i = 1; i <= e; i++)
  99.       r *= 10.0;
  100.  
  101.   if (sret) *sret = s;
  102.   return r * sign;
  103. }
  104.